package com.aiyige.page.my.order.myOrder;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.eventbus.EventOrderChanged;
import com.aiyige.model.OrderEntity;
import com.aiyige.model.eshop.Order;
import com.aiyige.model.eshop.ProductsBackup;
import com.aiyige.model.request.SearchBuyerOrdersOneTypeRequest;
import com.aiyige.model.response.OrderListResponse;
import com.aiyige.page.my.order.adapter.OrderListAdapter;
import com.aiyige.utils.HighLightWordUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.widget.CommonDataView;
import com.aiyige.utils.widget.MyEditText;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.vondear.rxtools.RxKeyboardTool;

import net.cachapa.expandablelayout.ExpandableLayout;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;

/**
 * Created by xiachao on 2017/11/29.
 */
@Route(path = ARouterConfig.SearchTypeMyOrderPage)
public class SearchTypeMyOrderPage extends BaseActivity implements CommonDataView.RetrofitStub {

    private static final String TAG = "SearchTypeMyOrderPage";

    @BindView(R.id.cdv)
    CommonDataView cdv;

    OrderListAdapter adapter;

    @BindView(R.id.et_search)
    MyEditText inputEt;

    @BindView(R.id.tv_cancel)
    TextView tvCancel;

    @BindView(R.id.cancelLayout)
    ExpandableLayout cancelLayout;

//    TextWatcher searchTextWatcher;
//
//    HandlerThread searchThread;
//    Handler searchHandler;
//    Handler mainHandler;

    @Autowired
    public int statusSet;
    @Autowired
    public String parentSearchValue;

    public static void start(int statusSet, String parentSearchValue) {
        ARouter.getInstance().build(ARouterConfig.SearchTypeMyOrderPage).withInt("statusSet", statusSet)
                .withString("parentSearchValue", parentSearchValue).navigation();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_search_type_my_orders);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        initViews();
    }

    private void initViews() {
        inputEt.getEditText().setText(parentSearchValue);
        adapter = new OrderListAdapter();
        adapter.setHideTypeLayout(true);
        cdv.config(adapter, this);
        cdv.doRefreshRequest();
        cdv.addItemDecoration(6, R.color.zwcolor_gray_f4f8f9);
        cdv.setRecyclerViewBgColor(ContextCompat.getColor(this, R.color.zwcolor_gray_f4f8f9));
        setAutoRegisterEventBus(true);
        inputEt.getEditText().setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    showSearchResultPanel();
                }
            }
        });
        inputEt.setActionSearch(new MyEditText.ActionCallback() {
            @Override
            public void actionSearch(String value) {
                doSearch(value);
            }
        });
    }


    @Override
    public Call<ResponseBody> call(long currentPage) {
        return SearchBuyerOrdersOneTypeRequest.newBuilder().keyWord(getSearchValue()).pageNum(currentPage).statusSet(Order.getOrderStatusValue(statusSet)).build();
    }

    private String getSearchValue() {
        return isEmpty(inputEt.getEditText().getText().toString().trim()) ? "" : inputEt.getEditText().getText().toString().trim();
    }

    @Override
    public CommonDataView.HandleResult handleResponse(String respJson, List resultList) {
        try {
            OrderListResponse homeResponse = JSON.parseObject(respJson, OrderListResponse.class);
            if (homeResponse == null) {
                throw new Exception("");
            } else {
                resultList.addAll(orderListToOrderEntityList(homeResponse.getContent()));
                return new CommonDataView.HandleResult(homeResponse.isLast());
            }
        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }

    }

    private List<OrderEntity> orderListToOrderEntityList(List<Order> list) {
        List<OrderEntity> orderEntityList = new ArrayList<>();
        if (!ListUtil.isEmpty(list)) {
            for (Order order : list) {
                try {
                    ProductsBackup productsBackup = order.getProductsBackup().get(0);
                    productsBackup.setTitle(HighLightWordUtil.highLight(productsBackup.getTitle(), getSearchValue()));
                } catch (Exception e) {

                }
                OrderEntity orderEntity =  new OrderEntity(order);
                orderEntity.setSearch(!TextUtils.isEmpty(getSearchValue()));
                orderEntityList.add(orderEntity);
            }
        }
        return orderEntityList;
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventOrderChanged(EventOrderChanged event) {
        if (adapter == null || adapter.getData() == null
                || adapter.getData().isEmpty()
                || event == null
                || TextUtils.isEmpty(event.getOrderEntity().getOrderId())) {
            return;
        }
        List<OrderEntity> list = adapter.getData();
        boolean find = false;
        for (int i = 0; i < list.size(); i++) {
            if (event.getOrderEntity().getOrderId().equals(list.get(i).getOrderId())) {
                list.remove(i);
                if (event.getOrderEntity().getStatus() != OrderEntity.STATUS_DELETED) {
                    list.add(i,event.getOrderEntity());
                }
                find = true;
                break;
            }
        }
        if (find) {
            adapter.notifyDataSetChanged();
        }
        if (cdv != null) {
            cdv.refresh();
        }
    }

    public void showSearchResultPanel() {
        cancelLayout.expand();
        cdv.setVisibility(View.VISIBLE);
    }

    public void hideSearchResultPanel() {
//        inputEt.getEditText().removeTextChangedListener(searchTextWatcher);
//        cancelLayout.collapse();
//        inputEt.getEditText().clearFocus();
//        KeyboardUtil.hideKeyboard(this, inputEt);
//        inputEt.getEditText().setText("");
//        adapter.setNewData(null);
//        cdv.setVisibility(View.INVISIBLE);
        finish();
    }

    private void doSearch(String value) {
        cdv.refresh();
        RxKeyboardTool.hideSoftInput(this);
    }


    @OnClick({R.id.tv_cancel, R.id.cancelLayout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_cancel:
            case R.id.cancelLayout:
                hideSearchResultPanel();
                break;
        }
    }
}
